package com.atguigu.gulimall.search.ljzgc;

import lombok.Data;

/**
 * @author daishaobo
 * @create 2021-04-02 20:49
 */
public class LinkDemo {


    public static Link delete(Link link,int n){
        if(link == null){
            return null;
        }
        Link for2 = link;
        Link result = link;
        int len = 1;
        while (link.hasNext()){
            len++;
            link = link.getNext();
        }

        int index = 2;
        int temp = len-n+1;
        if(temp == 1){
            return result.getNext();
        }
        Link parent = null;
        do{
            if(temp == index){
                Link link1 = for2.deleteNext();
                if(link1 != null){
                    for2.setNext(link1);
                }
                return result;
            }
            parent = for2;
            for2 = for2.getNext();
            index ++;
        }
        while (for2.hasNext());
        return result;
    }

    public static void main(String[] args) {
        Link l1 = new Link();
        l1.setValue(1);
        Link l2 = new Link();
        l2.setValue(2);
        Link l3 = new Link();
        l3.setValue(3);
        Link l4 = new Link();
        l4.setValue(4);
        Link l5 = new Link();
        l5.setValue(5);

        l1.setNext(l2);
        l2.setNext(l3);
        l3.setNext(l4);
        l4.setNext(l5);

        System.out.println(delete(l1, 4));
    }


}


@Data
class Link{

    private int value;
    private Link next;

    public void setNext(Link link){
        this.next = link;
    }
    public boolean hasNext(){
        return next != null;
    }
    public Link deleteNext(){
        if(next.hasNext()){
            Link nextNext = this.next.getNext();
            next = null;
            return nextNext;
        }else{
            this.next = null;
            return null;
        }
    }

    public String toString(){
        StringBuilder builder = new StringBuilder();

        builder.append(value);



        while (next.hasNext()){
            builder.append(next.getValue());
            next = next.getNext();

        }
        builder.append(next.getValue());
        return builder.toString();
    }



}